﻿/*
 * io.hpp
 *
 *  Created on: 2017年6月9日
 *      Author: work
 */

#ifndef _DM_OS_IO_IO_HPP_
#define _DM_OS_IO_IO_HPP_

#include <dm/types.hpp>
#include <dm/os/com/address.hpp>
#include <dm/timestamp.hpp>
#include <dm/counter.hpp>

namespace dm{
namespace os{
namespace io{

/**
 * IO基类
 */
class CIo{
	CIo( const CIo& );
public:
	typedef dm::TCounter<dm::uint64> counter_t;
	typedef com::CAddress::EType type_t;

	CIo();
	CIo( int fd );
	virtual ~CIo();

	bool open();
	bool open( const com::CAddress& addr );
	bool open( const char* addr );
	bool close();

	bool isOpen()const;

	bool isOpenable()const;

	virtual type_t type()const = 0;

	inline const char* typeName()const{
		return com::CAddress::typeString(type());
	}

	bool setAddress( const com::CAddress& addr );
	bool setAddress( const char* addr );

	inline const com::CAddress& address()const{
		return m_address;
	}

	int read( void* buf,const int& size );
	int write( const void* buf,const int& len );

	template<typename T>
	inline bool read( T& v ){
		return read(&v,sizeof(T))==sizeof(T);
	}

	template<typename T>
	inline bool write( const T& v ){
		return write(&v,sizeof(T))==sizeof(T);
	}

	inline const dm::CTimeStamp& lastOpen()const{
		return m_lastOpen;
	}

	inline const dm::CTimeStamp& lastClose()const{
		return m_lastClose;
	}

	inline const dm::CTimeStamp& lastTx()const{
		return m_lastTx;
	}

	inline const dm::CTimeStamp& lastRx()const{
		return m_lastRx;
	}

	inline const counter_t& txCounter()const{
		return m_txCnt;
	}

	inline const counter_t& rxCounter()const{
		return m_rxCnt;
	}

	inline void resetCounter(){
		resetTxCounter();
		resetRxCounter();
	}

	inline void resetTxCounter(){
		m_txCnt.reset();
	}

	inline void resetRxCounter(){
		m_rxCnt.reset();
	}

protected:
	virtual bool open_in( const com::CAddress& addr );

protected:
	friend class CMonitor;

	int m_fd;

	com::CAddress m_address;

	dm::CTimeStamp m_lastOpen;
	dm::CTimeStamp m_lastClose;
	dm::CTimeStamp m_lastTx;
	dm::CTimeStamp m_lastRx;

	counter_t m_txCnt;	// 发送计数器
	counter_t m_rxCnt;	// 接收计数器

	bool m_txBySend;
};

}
}
}

#endif /* INCLUDE_DM_OS_IO_IO_HPP_ */
